chrome.runtime.onInstalled.addListener(function () {
  alert('installed')
  chrome.storage.sync.set({ color: '#3aa757' }, function () {
    console.log('Value is set to #3aa757')
  })
})

// 获取当前选项卡ID
function getCurrentTabIdAsync() {
  return new Promise((resolve, reject) => {
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
      tabId = tabs.length ? tabs[0].id : null
      resolve(tabId)
    })
  })
}

chrome.storage.onChanged.addListener(function (changes, namespace) {
  for (var key in changes) {
    var storageChange = changes[key]
    console.log(
      'Storage key "%s" in namespace "%s" changed. ' + 'Old value was "%s", new value is "%s".',
      key,
      namespace,
      storageChange.oldValue,
      storageChange.newValue
    )
  }
})

let webMessage = document.getElementById('webMessage')

webMessage.addEventListener('click', function () {
  chrome.storage.sync.get('color', function (data) {
    webMessage.setAttribute('value', data.color)
    webMessage.style.backgroundColor = data.color
  })
  chrome.runtime.sendMessage('Hello', function (response) {
    console.log('response', response)
  })

  getCurrentTabIdAsync().then((tabId) => {
    // 动态执行JS文件
    chrome.tabs.executeScript(tabId, { file: 'js/action_script.js' })

    var port = chrome.tabs.connect(tabId, { name: 'test-connect' })
    port.postMessage({ question: '你是谁啊？' })
    port.postMessage({ type: 'PLAY_VIDEO' })

    port.onMessage.addListener(function (msg) {
      console.log('收到消息：' + msg.answer)
      if (msg.answer && msg.answer.startsWith('我是')) {
        port.postMessage({ question: '哦，原来是你啊！' })
      }
    })
  })
})

let buttonNote = document.querySelector('#actionGreet')
let buttonCancle = document.querySelector('#cancelGreet')
buttonNote.addEventListener('click', function () {
  console.log('开始刷课')
  getCurrentTabIdAsync().then(tabId => {
    chrome.tabs.executeScript(tabId, {code: 'filterGreet()'})
  })
})

buttonCancle.addEventListener('click', function () {
  console.log('取消刷课')
  getCurrentTabIdAsync().then(tabId => {
    chrome.tabs.executeScript(tabId, {code: 'canclePostAction()'})
  })
})
